/******************************************************************************
* Copyright (C) 2016, Huada Semiconductor Co.,Ltd All rights reserved.
*
* This software is owned and published by:
* Huada Semiconductor Co.,Ltd ("HDSC").
*
* BY DOWNLOADING, INSTALLING OR USING THIS SOFTWARE, YOU AGREE TO BE BOUND
* BY ALL THE TERMS AND CONDITIONS OF THIS AGREEMENT.
*
* This software contains source code for use with HDSC
* components. This software is licensed by HDSC to be adapted only
* for use in systems utilizing HDSC components. HDSC shall not be
* responsible for misuse or illegal use of this software for devices not
* supported herein. HDSC is providing this software "AS IS" and will
* not be responsible for issues arising from incorrect user implementation
* of the software.
*
* Disclaimer:
* HDSC MAKES NO WARRANTY, EXPRESS OR IMPLIED, ARISING BY LAW OR OTHERWISE,
* REGARDING THE SOFTWARE (INCLUDING ANY ACOOMPANYING WRITTEN MATERIALS),
* ITS PERFORMANCE OR SUITABILITY FOR YOUR INTENDED USE, INCLUDING,
* WITHOUT LIMITATION, THE IMPLIED WARRANTY OF MERCHANTABILITY, THE IMPLIED
* WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE, AND THE IMPLIED
* WARRANTY OF NONINFRINGEMENT.
* HDSC SHALL HAVE NO LIABILITY (WHETHER IN CONTRACT, WARRANTY, TORT,
* NEGLIGENCE OR OTHERWISE) FOR ANY DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION,
* LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY LOSS) ARISING FROM USE OR
* INABILITY TO USE THE SOFTWARE, INCLUDING, WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL OR CONSEQUENTIAL DAMAGES OR LOSS OF DATA,
* SAVINGS OR PROFITS,
* EVEN IF Disclaimer HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* YOU ASSUME ALL RESPONSIBILITIES FOR SELECTION OF THE SOFTWARE TO ACHIEVE YOUR
* INTENDED RESULTS, AND FOR THE INSTALLATION OF, USE OF, AND RESULTS OBTAINED
* FROM, THE SOFTWARE.
*
* This software may be replicated in part or whole for the licensed use,
* with the restriction that this Disclaimer and Copyright notice must be
* included with each copy of this software, whether used in part or whole,
* at all times.
*/
/******************************************************************************/
/** \file main.c
 **
 ** A detailed description is available at
 ** @link Sample Group Some description @endlink
 **
 **   - 2016-02-16  1.0  XYZ First version for Device Driver Library of Module.
 **
 ******************************************************************************/

/******************************************************************************
 * Include files
 ******************************************************************************/

#include "FreeRTOS.h"
#include "task.h"
#include "timers.h"
#include "queue.h"
#include "semphr.h"
#include "event_groups.h"
#include "FreeRTOSConfig.h"

#include "gpio.h"
/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/
#define LED_TASK_STACK_SIZE  64
#define KEY_TASK_STACK_SIZE  64
/******************************************************************************
 * Global variable definitions (declared in header file with 'extern')
 ******************************************************************************/

/******************************************************************************
 * Local type definitions ('typedef')
 ******************************************************************************/

/******************************************************************************
 * Local function prototypes ('static')
 ******************************************************************************/

/******************************************************************************
 * Local variable definitions ('static')                                                   *
 ******************************************************************************/
/* 空闲任务任务堆栈 */
static StackType_t Idle_Task_Stack[configMINIMAL_STACK_SIZE];
/* 空闲任务控制块 */
static StaticTask_t Idle_Task_TCB;

/* 定时器任务堆栈 */
//static StackType_t Timer_Task_Stack[configTIMER_TASK_STACK_DEPTH];
/* 定时器任务控制块 */
//static StaticTask_t Timer_Task_TCB;

/* LED任务(TASK1)任务堆栈 */
static StackType_t LED_Task_Stack[LED_TASK_STACK_SIZE];
/* LED任务(TASK1)任务控制块 */
static StaticTask_t LED_Task_TCB;

/* 按键任务(TASK2)任务堆栈 */
static StackType_t KEY_Task_Stack[KEY_TASK_STACK_SIZE];
/* 按键任务(TASK2)任务控制块 */
static StaticTask_t KEY_Task_TCB;
/******************************************************************************
 * Local pre-processor symbols/macros ('#define')
 ******************************************************************************/

/*****************************************************************************
 * Function implementation - global ('extern') and local ('static')
 ******************************************************************************/
static void Gpio_Config(void);
 
 /**
 ******************************************************************************
 ** \brief  获取空闲任务的任务堆栈和任务控制块内存（使用静态内存分配时需要用户实现此函数）
 ** \param  ppxTimerTaskTCBBuffer : 任务控制块内存
 **         ppxTimerTaskStackBuffer : 任务堆栈内存
 **         pulTimerTaskStackSize : 任务堆栈大小
 ** \return none
 **
 ** This sample
 **
 ******************************************************************************/
void vApplicationGetIdleTaskMemory( StaticTask_t **ppxIdleTaskTCBBuffer,
                                    StackType_t **ppxIdleTaskStackBuffer,
                                    uint32_t *pulIdleTaskStackSize)
{
    *ppxIdleTaskTCBBuffer = &Idle_Task_TCB;         /* 任务控制块内存 */
    *ppxIdleTaskStackBuffer = Idle_Task_Stack;      /* 任务堆栈内存 */
    *pulIdleTaskStackSize=configMINIMAL_STACK_SIZE; /* 任务堆栈大小 */
}
 
 /**
 ******************************************************************************
 ** \brief  获取定时器任务的任务堆栈和任务控制块内存（使用静态内存分配时需要用户实现此函数）
 ** \param  ppxTimerTaskTCBBuffer : 任务控制块内存
 **         ppxTimerTaskStackBuffer : 任务堆栈内存
 **         pulTimerTaskStackSize : 任务堆栈大小
 ** \return none
 **
 ** This sample
 **
 ******************************************************************************/
//void vApplicationGetTimerTaskMemory( StaticTask_t **ppxTimerTaskTCBBuffer,
//                                     StackType_t **ppxTimerTaskStackBuffer,
//                                     uint32_t *pulTimerTaskStackSize)
//{
//    *ppxTimerTaskTCBBuffer=&Timer_Task_TCB;/* 任务控制块内存 */
//    *ppxTimerTaskStackBuffer=Timer_Task_Stack;/* 任务堆栈内存 */
//    *pulTimerTaskStackSize=configTIMER_TASK_STACK_DEPTH;/* 任务堆栈大小 */
//}


void vTask1(void *pvParameters)
{
    while (1)
    {
		taskENTER_CRITICAL();
        Gpio_ClrIO(GpioPortD, GpioPin5);                       /* LED熄灭 */
		taskEXIT_CRITICAL();
		
		vTaskDelay(500/portTICK_RATE_MS);                      /* 延时500ms，延时期间任务进入阻塞态 */

		taskENTER_CRITICAL();
        Gpio_SetIO(GpioPortD, GpioPin5);                       /* LED点亮 */
		taskEXIT_CRITICAL();
		
		vTaskDelay(500/portTICK_RATE_MS);                      /* 延时500ms，延时期间任务进入阻塞态 */
    }
 }
 
 void vTask2(void *pvParameters)
 {
    while (1)
    {
        while (FALSE == Gpio_GetInputIO(GpioPortD, GpioPin4))  /* 按键按下 */
        {
			taskENTER_CRITICAL();
            Gpio_ClrIO(GpioPortD, GpioPin5);                   /* LED熄灭 */
			taskEXIT_CRITICAL();
			
            vTaskPrioritySet(NULL, 2);                         /* 设置当前任务优先级为2 */
            delay1ms(5000);                                    /* 延时5s,延时期间不进入阻塞态 */
            vTaskPrioritySet(NULL, 1);                         /* 设置当前任务优先级为2 */
            taskYIELD();                                       /* 通知调度器切换到其它任务 */
        }
    }
 }
/**
 ******************************************************************************
 ** \brief  Main function of project
 **
 ** \return uint32_t return value, if needed
 **
 ** This sample
 **
 ******************************************************************************/
int32_t main(void)
{
	Gpio_Config();
	
	xTaskCreateStatic(vTask1, "Task1", LED_TASK_STACK_SIZE, NULL, 1, LED_Task_Stack, &LED_Task_TCB);           /* 创建任务1 */
	xTaskCreateStatic(vTask2, "Task2", KEY_TASK_STACK_SIZE, NULL, 1, KEY_Task_Stack, &KEY_Task_TCB);          /* 创建任务2 */
	vTaskStartScheduler();                                      /* 启动任务调度 */
	while(1);
}

/******************************************************************************
 * EOF (not truncated)
 ******************************************************************************/

/* CPU IO口配置（包含LED灯和按键的配置）*/
static void Gpio_Config(void)
{
    stc_gpio_config_t stcGpioCfg;
	
    Sysctrl_SetPeripheralGate(SysctrlPeripheralGpio, TRUE);     /* 打开GPIO外设时钟门控 */
    
    stcGpioCfg.enDir = GpioDirIn;                               /* 端口方向配置->输入 */    
    stcGpioCfg.enDrv = GpioDrvL;                                /* 端口驱动能力配置->高驱动能力 */
    stcGpioCfg.enPuPd = GpioPu;                                 /* 端口上下拉配置->上拉 */
    stcGpioCfg.enOD = GpioOdDisable;                            /* 端口开漏输出配置->开漏输出关闭 */
    stcGpioCfg.enCtrlMode = GpioAHB;                            /* 端口输入/输出值寄存器总线控制模式配置->AHB */
    
    Gpio_Init(GpioPortD, GpioPin4, &stcGpioCfg);                /* GPIO IO PD04初始化(PD04在STK上外接KEY(USER)) */
    
    stcGpioCfg.enDir = GpioDirOut;                              /* 端口方向配置->输出(其它参数与以上（输入）配置参数一致) */
    stcGpioCfg.enPuPd = GpioPd;                                 /* 端口上下拉配置->下拉 */

    Gpio_Init(GpioPortD, GpioPin5, &stcGpioCfg);                /* GPIO IO PD05初始化(PD05在STK上外接LED(LED3)) */
}
